package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.pojo.Player;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
@Data
public class TokenUtil {
    @Value("${mytoken.sign}")
    private   String  sign;


    @Value("${mytoken.expiration}")
    private   long etime;

    private  Map<String, Player> tokenMap=new HashMap<String, Player>();

    //根据登录的用户id返回token
    public  String generateToken(Player player){
        String token= JWT.create()
                .withClaim("id",player.getId())
                .withExpiresAt(new Date(System.currentTimeMillis()+etime))
                .sign(Algorithm.HMAC256(sign));
        return token;
    }
    //解析token，返回用户id
    public  Integer verify(String token){
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(sign)).build();
        DecodedJWT verify=jwtVerifier.verify(token);
        Integer id =verify.getClaim("id").asInt();
        return id;
    }

}
